﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using DosTexPrj.Core.Models;
using DosTexPrj.Core.RepositoriesInterface;
using DosTexPrj.Implement.NHibernate;
using DosTexPrj.UI.WinForm.Commons;
using DosTexPrj.UI.WinForm.Models;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace DosTexPrj.UI.WinForm
{
    public partial class CustomerOrderForm : Form
    {
        #region --- Private methods ---

        private IOrderRepository _orderRepository;
        private ICustomerRepository _customerRepository;
        private IRepository _repository;
        private IList<OrderDetail> _currentOrdersDetail;
        private Order _currentOrder;

        #endregion --- Private methods ---

        #region --- Properties ---

        public Order CurrentOrder
        {
            private get
            {
                return this._currentOrder;
            }
            set { this._currentOrder = value; }
        }

        #endregion --- Properties ---

        #region --- Constructors ---

        public CustomerOrderForm()
        {
            InitializeComponent();
            _orderRepository = MyServiceLocator.DoGetInstance<IOrderRepository>();
            _customerRepository = MyServiceLocator.DoGetInstance<ICustomerRepository>();
            _repository = MyServiceLocator.DoGetInstance<IRepository>();
            this._currentOrdersDetail = new List<OrderDetail>();
            this.txtPayAfter.KeyPress += new KeyPressEventHandler(txtPayAfter_KeyPress);
        }

        private void txtPayAfter_KeyPress(object sender, KeyPressEventArgs e)
        {
            Common.HandlingNumberTextbox(e);
        }

        public CustomerOrderForm(Order orderToEdit)
            : this()
        {
            this._currentOrder = orderToEdit;
        }

        private bool ClearForm
        {
            set
            {
                txtCustomerAddress.Text = string.Empty;
                txtCustomerName.Text = string.Empty;
                txtCustomerPhone.Text = string.Empty;
                txtFreight.Text = string.Empty;
                txtOrderNo.Text = (GetMaxOrderId() + 1).ToString();
                txtOrderNo.ReadOnly = true;
                txtPayAfter.Text = string.Empty;

                chkPayAfter.Checked = false;
                chkPayBeforeDelivery.Checked = false;

                dtpDeliveryDate.Value = DateTime.Now;
                dtpOrderDate.Value = DateTime.Now;

                lvOrderDetail.Items.Clear();

                LoadCustomer();
                LoadDeliveryMethod();
                LoadPaymentMethod();
                LoadOrderStatus();
            }
        }

        #endregion --- Constructors ---

        private void CustomerOrderListForm_Load(object sender, EventArgs e)
        {
            LoadCustomerOrderList();
            CreateFormTitle();

            LoadFilterCustomer();
            LoadFilterOrderStatus();

            txtCustomerAddress.Enabled = txtCustomerName.Enabled = txtCustomerPhone.Enabled = btnSave.Enabled = false;
            this._currentOrdersDetail = new List<OrderDetail>();
        }

        #region Order List Grid

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (lvOrderList.SelectedItems.Count < 1)
            {
                MessageBox.Show("Please select an Order on Order List for printing", "Warning", MessageBoxButtons.OK);
                return;
            }

            CustomerOrderModel selectedOrderModel = (CustomerOrderModel)lvOrderList.SelectedItems[0].Tag;
            Order order = this._repository.FindByKey<Order>(selectedOrderModel.Id);
            if (order != null)
            {
                if (!Directory.Exists(@"C:\pdf"))
                {
                    Directory.CreateDirectory(@"C:\pdf");
                }

                string filePath = @"C:\pdf\printing-customerorder" + order.Id.ToString() + ".pdf";

                DoPrinting(order, filePath);

                if (File.Exists(filePath))
                {
                    System.Diagnostics.ProcessStartInfo printObject = new System.Diagnostics.ProcessStartInfo();
                    printObject.Verb = "print";
                    printObject.FileName = filePath;
                    printObject.UseShellExecute = true;
                    System.Diagnostics.Process.Start(printObject);
                }
            }
            else
            {
                MessageBox.Show("Please select an Order on Order List for printing", "Warning", MessageBoxButtons.OK);
                return;
            }
        }

        private void lvOrderList_DoubleClick(object sender, EventArgs e)
        {
            if (lvOrderList.SelectedItems.Count < 1)
            {
                return;
            }
            try
            {
                CustomerOrderModel selectedOrderModel = (CustomerOrderModel)lvOrderList.SelectedItems[0].Tag;
                this.CurrentOrder = _repository.FindByKey<Order>(selectedOrderModel.Id);
                this._currentOrdersDetail = this.CurrentOrder.OrderDetails;
                PushDataToForm(this.CurrentOrder);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        private void chkAll_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAll.Checked)
            {
                chkInMonth.Checked = !chkAll.Checked;
                LoadCustomerOrderList();
            }
            else
            {
                LoadCustomerOrderList();
            }
        }

        private void chkInMonth_CheckedChanged(object sender, EventArgs e)
        {
            if (chkInMonth.Checked)
            {
                chkAll.Checked = !chkInMonth.Checked;
                LoadCustomerOrderList();
            }
            else
            {
                LoadCustomerOrderList();
            }
        }

        private void dtpOrderMonth_ValueChanged(object sender, EventArgs e)
        {
            LoadCustomerOrderList();
        }

        private void cboCustomerFilter_SelectedIndexChanged(object sender, EventArgs e)
        {
            chkAll.Checked = chkInMonth.Checked = false;
        }

        #endregion Order List Grid

        #region Order detail

        private void btnAddNew_Click(object sender, EventArgs e)
        {
            ClearForm = true;
            btnSave.Enabled = true;
            this.CurrentOrder = new Order();
            this._currentOrdersDetail = new List<OrderDetail>();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (lvOrderList.SelectedItems.Count < 1)
            {
                MessageBox.Show("Please select an Order on Order List ", "Warning", MessageBoxButtons.OK);
                return;
            }
            try
            {
                CustomerOrderModel selectedOrderModel = (CustomerOrderModel)lvOrderList.SelectedItems[0].Tag;
                if (MessageBox.Show("Are you sure want to delete Order No. " + selectedOrderModel.Id + "?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    //_repository.Delete<Order>(x => x.Id == selectedOrderModel.Id);
                    var order = this._repository.FindByKey<Order>(selectedOrderModel.Id);
                    this._orderRepository.DeleteOrder(order);
                    LoadCustomerOrderList();
                    ClearForm = true;
                    MessageBox.Show("Delete successfully.", "Warning", MessageBoxButtons.OK);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!CheckValidate())
                return;
            //Kim edited: Do not allow to create Order without OrderDetail
            if (this._currentOrdersDetail == null || this._currentOrdersDetail.Count == 0)
            {
                MessageBox.Show("Please add detail(s) before create order");
                return;
            }
            //End edited by Kim
            this.CreateOrder();
            btnSave.Enabled = false;
            ClearForm = true;
        }

        private void chkPayBeforeDelivery_CheckedChanged(object sender, EventArgs e)
        {
            if (chkPayBeforeDelivery.Checked)
            {
                chkPayAfter.Checked = !chkPayBeforeDelivery.Checked;
                txtPayAfter.Text = string.Empty;
                txtPayAfter.ReadOnly = true;
            }
        }

        private void chkPayAfter_CheckedChanged(object sender, EventArgs e)
        {
            if (chkPayAfter.Checked)
            {
                chkPayBeforeDelivery.Checked = !chkPayAfter.Checked;
                txtPayAfter.ReadOnly = false;
            }
        }

        private void btnAddOrderDetail_Click(object sender, EventArgs e)
        {
            //Kim edited: do not allow add detail if no order was selected
            if (this._currentOrder == null)
            {
                MessageBox.Show("Please select order after add detail");
                return;
            }
            //End edited by Kim
            CustomerOrderDetailForm orderDetailForm = new CustomerOrderDetailForm();
            orderDetailForm.FormClosed += new FormClosedEventHandler(orderDetailForm_FormClosed);
            orderDetailForm.StartPosition = FormStartPosition.CenterParent;
            orderDetailForm.ShowDialog();
            LoadOrderDetailList();
        }

        private void orderDetailForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            if ((sender as CustomerOrderDetailForm).CurrentOrderDetail == null) return;
            this._currentOrdersDetail.Add((sender as CustomerOrderDetailForm).CurrentOrderDetail);
        }

        private void btnDeleteOrderDetail_Click(object sender, EventArgs e)
        {
            if (lvOrderDetail.SelectedItems.Count < 1)
            {
                MessageBox.Show("Please select an Order detail on Order Detail List ", "Warning", MessageBoxButtons.OK);
                return;
            }
            try
            {
                OrderDetail selectedOrderDetail = (OrderDetail)lvOrderDetail.SelectedItems[0].Tag;

                if (MessageBox.Show("Are you sure want to delete this?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (selectedOrderDetail.Id > 0)
                    {
                        _repository.Delete<OrderDetail>(x => x.Id == selectedOrderDetail.Id);
                    }
                    this._currentOrdersDetail.Remove(selectedOrderDetail);
                    // Get selected order to refresh detail grid
                    if (this.lvOrderList.SelectedItems.Count >= 1)
                    {
                        CustomerOrderModel selectedOrderModel = (CustomerOrderModel)lvOrderList.SelectedItems[0].Tag;
                    }
                    PushDataToForm(this.CurrentOrder);
                    MessageBox.Show("Delete successfully.", "Warning", MessageBoxButtons.OK);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        private void btnAddCustomer_Click(object sender, EventArgs e)
        {
            CustomerForm customerForm = new CustomerForm();
            customerForm.StartPosition = FormStartPosition.CenterParent;
            customerForm.ShowDialog();
            LoadCustomer();
            LoadFilterCustomer();
        }

        private void btnAddPaymentMethod_Click(object sender, EventArgs e)
        {
            PaymentMethodForm paymentMethodForm = new PaymentMethodForm();
            paymentMethodForm.StartPosition = FormStartPosition.CenterParent;
            paymentMethodForm.ShowDialog();
            LoadPaymentMethod();
        }

        private void btnAddDeliveryMethod_Click(object sender, EventArgs e)
        {
            DeliveryMethodForm deliveryMethodForm = new DeliveryMethodForm();
            deliveryMethodForm.StartPosition = FormStartPosition.CenterParent;
            deliveryMethodForm.ShowDialog();
            LoadDeliveryMethod();
        }

        private void cboCustomer_SelectedIndexChanged(object sender, EventArgs e)
        {
            Customer customer = (Customer)cboCustomer.SelectedItem;
            if (customer != null)
            {
                txtCustomerName.Text = customer.CustomerName;
                txtCustomerAddress.Text = customer.Address;
                txtCustomerPhone.Text = customer.PhoneNumber;
            }
        }

        #endregion Order detail

        #region Functions

        private void DoPrinting(Order order, string filePath)
        {
            Font fBold = FontFactory.GetFont("Tahoma", 11, iTextSharp.text.Font.BOLD);
            Font fNormal = FontFactory.GetFont("Tahoma", 11);
            Font fNormalySmall = FontFactory.GetFont("Tahoma", 9);
            Font fBig = FontFactory.GetFont("Tahoma", 16, iTextSharp.text.Font.BOLD);

            var pdfFile = new Document(PageSize.A4);
            PdfWriter.GetInstance(pdfFile, new FileStream(filePath, FileMode.Create));

            pdfFile.Open();
            //Add Title
            Printing.AddTitleToPdf(pdfFile, "ORDER", fBig);
            // Add Order Info
            OrderPrinting.AddOrderInfoToPdf(pdfFile, order, fNormal, fBold);
            // Add Customer Info
            OrderPrinting.AddCustomerInfoToPdf(pdfFile, order.Customer, fNormal, fBold);
            // Add Conditions
            OrderPrinting.AddConditionInfoToPdf(pdfFile, order, fNormal, fBold);
            // Add Order detal
            OrderPrinting.AddOrderDetailToPdf(pdfFile, order.OrderDetails, fNormalySmall, fBold);
            // Add Signatures
            Printing.AddSignaturesToPdf(pdfFile, fBold, "Notes", "Customer Confirmation");
            pdfFile.Close();
        }

        private bool CheckValidate()
        {
            error.Clear();
            bool flag = true;
            if (!Common.IsCorrectDate(dtpOrderDate.Value, dtpDeliveryDate.Value, "Order Date can not be later than Delivery Date!", dtpDeliveryDate, error))
                flag = false;
            if (!Common.IsBlankCombobox(cboCustomer, "Required Field", error))
                flag = false;
            if (!Common.IsBlankCombobox(cboDeliveryMethod, "Required Field", error))
                flag = false;
            if (!Common.IsBlankCombobox(cboOrderStatus, "Required Field", error))
                flag = false;
            if (!Common.IsBlankCombobox(cboPaymentMethod, "Required Field", error))
                flag = false;

            return flag;
        }

        private void CreateFormTitle()
        {
            ctrTitle.FormTitle = "CUSTOMER ORDER INFORMATIONS";
            ctrTitle.BackColor = System.Drawing.Color.White;
        }

        private void PushDataToForm(Order order)
        {
            LoadCustomer();
            LoadDeliveryMethod();
            LoadPaymentMethod();
            LoadOrderStatus();

            if (order.Customer != null)
            {
                cboCustomer.SelectedValue = order.Customer.Id;
                txtCustomerAddress.Text = order.Customer.Address;
                txtCustomerName.Text = order.Customer.CustomerName;
                txtCustomerPhone.Text = order.Customer.PhoneNumber;
            }
            if (order.DeliveryMethod != null)
            {
                cboDeliveryMethod.SelectedValue = order.DeliveryMethod.Id;
            }
            if (order.PaymentMethod != null)
            {
                cboPaymentMethod.SelectedValue = order.PaymentMethod.Id;
            }
            if (order.OrderStatus != null)
            {
                cboOrderStatus.SelectedValue = order.OrderStatus.Id;
            }
            txtFreight.Text = order.Freight;
            txtOrderNo.Text = order.Id > 0 ? order.Id.ToString() : txtOrderNo.Text;
            txtOrderNo.ReadOnly = true;

            if (!order.IsDeliveredBefore && order.NumberOfDateExtensionDelivery == 0)
            {
                chkPayBeforeDelivery.Checked = false;
                chkPayAfter.Checked = false;
                txtPayAfter.Text = string.Empty;
            }
            else if (!order.IsDeliveredBefore && order.NumberOfDateExtensionDelivery != 0)
            {
                chkPayAfter.Checked = true;
                txtPayAfter.Text = order.NumberOfDateExtensionDelivery.ToString();
            }
            else if (order.IsDeliveredBefore)
            {
                chkPayBeforeDelivery.Checked = true;
                txtPayAfter.Text = string.Empty;
            }

            dtpDeliveryDate.Value = order.DeliveryDate == DateTime.MinValue ? DateTime.Today : order.DeliveryDate;
            dtpOrderDate.Value = order.OrderDate == DateTime.MinValue ? DateTime.Today : order.OrderDate;

            LoadOrderDetailList();

            btnSave.Enabled = true;
        }

        private int GetMaxOrderId()
        {
            var orders = this._orderRepository.LoadAllOrder(); ;
            int maxOrderId = 0;
            try
            {
                maxOrderId = (from order in orders
                              select order).Max(m => m.Id);
            }
            catch
            {
                return maxOrderId;
            }
            return maxOrderId;
        }

        private void LoadCustomerOrderList()
        {
            var orders = _orderRepository.LoadAllOrder();
            IList<CustomerOrderModel> orderSource = new List<CustomerOrderModel>();

            // Get orders in selected month
            if (chkInMonth.Checked)
            {
                // Get order by customer
                if (cboOrderStatusFilter.SelectedIndex > 0 && cboCustomerFilter.SelectedIndex > 0)
                {
                    orderSource = (from order in orders
                                   where order.OrderDate.Month == dtpOrderMonth.Value.Month && order.OrderStatus.Id == ((OrderStatus)cboOrderStatusFilter.SelectedItem).Id && order.Customer.Id == ((Customer)cboCustomerFilter.SelectedItem).Id
                                   select new CustomerOrderModel
                                   {
                                       Id = order.Id,
                                       CustomerName = order.Customer.CustomerName,
                                       OrderDate = order.OrderDate,
                                       DeliveryDate = order.DeliveryDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
                else if (cboCustomerFilter.SelectedIndex > 0)
                {
                    orderSource = (from order in orders
                                   where order.OrderDate.Month == dtpOrderMonth.Value.Month && order.Customer.Id == ((Customer)cboCustomerFilter.SelectedItem).Id
                                   select new CustomerOrderModel
                                   {
                                       Id = order.Id,
                                       CustomerName = order.Customer.CustomerName,
                                       OrderDate = order.OrderDate,
                                       DeliveryDate = order.DeliveryDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
                // Get order by order status
                else if (cboOrderStatusFilter.SelectedIndex > 0)
                {
                    orderSource = (from order in orders
                                   where order.OrderDate.Month == dtpOrderMonth.Value.Month && order.OrderStatus.Id == ((OrderStatus)cboOrderStatusFilter.SelectedItem).Id
                                   select new CustomerOrderModel
                                   {
                                       Id = order.Id,
                                       CustomerName = order.Customer.CustomerName,
                                       OrderDate = order.OrderDate,
                                       DeliveryDate = order.DeliveryDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
                else
                {
                    orderSource = (from order in orders
                                   where order.OrderDate.Month == dtpOrderMonth.Value.Month
                                   select new CustomerOrderModel
                                   {
                                       Id = order.Id,
                                       CustomerName = order.Customer.CustomerName,
                                       OrderDate = order.OrderDate,
                                       DeliveryDate = order.DeliveryDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
            }
            // Get all
            else
            {
                // Get order by customer
                if (cboOrderStatusFilter.SelectedIndex > 0 && cboCustomerFilter.SelectedIndex > 0)
                {
                    orderSource = (from order in orders
                                   where order.OrderStatus.Id == ((OrderStatus)cboOrderStatusFilter.SelectedItem).Id && order.Customer.Id == ((Customer)cboCustomerFilter.SelectedItem).Id
                                   select new CustomerOrderModel
                                   {
                                       Id = order.Id,
                                       CustomerName = order.Customer.CustomerName,
                                       OrderDate = order.OrderDate,
                                       DeliveryDate = order.DeliveryDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
                else if (cboCustomerFilter.SelectedIndex > 0)
                {
                    orderSource = (from order in orders
                                   where order.Customer.Id == ((Customer)cboCustomerFilter.SelectedItem).Id
                                   select new CustomerOrderModel
                                   {
                                       Id = order.Id,
                                       CustomerName = order.Customer.CustomerName,
                                       OrderDate = order.OrderDate,
                                       DeliveryDate = order.DeliveryDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
                // Get order by order status
                else if (cboOrderStatusFilter.SelectedIndex > 0)
                {
                    orderSource = (from order in orders
                                   where order.OrderStatus.Id == ((OrderStatus)cboOrderStatusFilter.SelectedItem).Id
                                   select new CustomerOrderModel
                                   {
                                       Id = order.Id,
                                       CustomerName = order.Customer.CustomerName,
                                       OrderDate = order.OrderDate,
                                       DeliveryDate = order.DeliveryDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
                else
                {
                    orderSource = (from order in orders
                                   select new CustomerOrderModel
                                   {
                                       Id = order.Id,
                                       CustomerName = order.Customer.CustomerName,
                                       OrderDate = order.OrderDate,
                                       DeliveryDate = order.DeliveryDate,
                                       DeliveryStatus = order.OrderStatus.OrderStatusName
                                   }).ToList();
                }
            }

            if (orderSource != null)
            {
                lvOrderList.Items.Clear();

                for (int i = 0; i < orderSource.Count; i++)
                {
                    ListViewItem item = lvOrderList.Items.Add(orderSource[i].Id.ToString());
                    item.Tag = orderSource[i];
                    item.SubItems.Add(orderSource[i].CustomerName);
                    item.SubItems.Add(orderSource[i].OrderDate.ToShortDateString());
                    item.SubItems.Add(orderSource[i].DeliveryDate.ToShortDateString());
                    item.SubItems.Add(orderSource[i].DeliveryStatus);
                }
            }
        }

        private void LoadOrderDetailList()
        {
            if (this._currentOrdersDetail != null)
            {
                lvOrderDetail.Items.Clear();

                for (int i = 0; i < this._currentOrdersDetail.Count; i++)
                {
                    ListViewItem item = lvOrderDetail.Items.Add(i + 1 + "");
                    item.Tag = this._currentOrdersDetail[i];
                    item.SubItems.Add(this._currentOrdersDetail[i].FabricType.FabricTypeName);
                    item.SubItems.Add(this._currentOrdersDetail[i].Color.ToString());
                    item.SubItems.Add(this._currentOrdersDetail[i].Composition.CompostionName);
                    item.SubItems.Add(this._currentOrdersDetail[i].MtQuantity.ToString());
                    item.SubItems.Add(this._currentOrdersDetail[i].KgQuantity.ToString());
                    item.SubItems.Add(this._currentOrdersDetail[i].CuttableWidth.ToString());
                    item.SubItems.Add(this._currentOrdersDetail[i].Weight.ToString());

                    // (1000 / width / weight * 100)-5%
                    double yield = (1000f / this._currentOrdersDetail[i].CuttableWidth / this._currentOrdersDetail[i].Weight * 100) - (((1000f / this._currentOrdersDetail[i].CuttableWidth / this._currentOrdersDetail[i].Weight * 100) / 100) * 5);
                    item.SubItems.Add(Math.Round(yield, 2).ToString());

                    item.SubItems.Add(this._currentOrdersDetail[i].Price.ToString());
                }
            }
        }

        private void CreateOrder()
        {
            var order = this.CurrentOrder;
            order.Customer = (Customer)cboCustomer.SelectedItem;
            order.DeliveryDate = dtpDeliveryDate.Value;
            order.Freight = txtFreight.Text.Trim();
            order.IsDeliveredBefore = chkPayBeforeDelivery.Checked;
            order.NumberOfDateExtensionDelivery = chkPayAfter.Checked == true ? int.Parse(txtPayAfter.Text.Trim()) : 0;
            order.OrderDate = dtpOrderDate.Value;
            order.OrderStatus = (OrderStatus)cboOrderStatus.SelectedItem;
            order.PaymentMethod = (PaymentMethod)cboPaymentMethod.SelectedItem;
            order.DeliveryMethod = (DeliveryMethod)cboDeliveryMethod.SelectedItem;
            order.OrderDetails = this._currentOrdersDetail;
            try
            {
                _customerRepository.Save<Order>(order);
                LoadCustomerOrderList();
                MessageBox.Show("Save successfully.", "Warning", MessageBoxButtons.OK);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        private void LoadCustomer()
        {
            try
            {
                var customerData = _repository.GetAll<Customer>();
                IList<Customer> customers = new List<Customer>();

                customers = (from c in customerData
                             select new Customer
                             {
                                 Id = c.Id,
                                 CustomerName = c.CustomerName,
                                 Address = c.Address,
                                 PhoneNumber = c.PhoneNumber
                             }).ToList();

                if (customers.Count > -1)
                {
                    cboCustomer.DataSource = customers;
                    cboCustomer.DisplayMember = "CustomerName";
                    cboCustomer.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void LoadDeliveryMethod()
        {
            try
            {
                var deliveryMethodData = _repository.GetAll<DeliveryMethod>();
                IList<DeliveryMethod> deliveryMethods = new List<DeliveryMethod>();

                deliveryMethods = (from d in deliveryMethodData
                                   select new DeliveryMethod
                                   {
                                       Id = d.Id,
                                       DeliveryMethodName = d.DeliveryMethodName
                                   }).ToList();

                if (deliveryMethods.Count > -1)
                {
                    cboDeliveryMethod.DataSource = deliveryMethods;
                    cboDeliveryMethod.DisplayMember = "DeliveryMethodName";
                    cboDeliveryMethod.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void LoadPaymentMethod()
        {
            try
            {
                var paymentMethodData = _repository.GetAll<PaymentMethod>();
                IList<PaymentMethod> paymentMethods = new List<PaymentMethod>();

                paymentMethods = (from d in paymentMethodData
                                  select new PaymentMethod
                                  {
                                      Id = d.Id,
                                      PaymentMethodName = d.PaymentMethodName
                                  }).ToList();

                if (paymentMethods.Count > -1)
                {
                    cboPaymentMethod.DataSource = paymentMethods;
                    cboPaymentMethod.DisplayMember = "PaymentMethodName";
                    cboPaymentMethod.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void LoadOrderStatus()
        {
            try
            {
                var orderStatusData = _repository.GetAll<OrderStatus>();
                IList<OrderStatus> orderStatus = new List<OrderStatus>();

                orderStatus = (from d in orderStatusData
                               select new OrderStatus
                               {
                                   Id = d.Id,
                                   OrderStatusName = d.OrderStatusName
                               }).ToList();

                if (orderStatus.Count > -1)
                {
                    cboOrderStatus.DataSource = orderStatus;
                    cboOrderStatus.DisplayMember = "OrderStatusName";
                    cboOrderStatus.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void LoadFilterCustomer()
        {
            try
            {
                var customerData = _repository.GetAll<Customer>();
                IList<Customer> customers = new List<Customer>();
                IList<Customer> customersResult = new List<Customer>();

                customers = (from c in customerData
                             select new Customer
                             {
                                 Id = c.Id,
                                 CustomerName = c.CustomerName,
                                 Address = c.Address,
                                 PhoneNumber = c.PhoneNumber
                             }).ToList();

                if (customers.Count > 0)
                {
                    customersResult.Add(new Customer { Id = -1, CustomerName = "-Select a customer-", Address = string.Empty, PhoneNumber = string.Empty });

                    for (int i = 0; i < customers.Count; i++)
                    {
                        customersResult.Add(customers[i]);
                    }
                    cboCustomerFilter.DataSource = customersResult;
                    cboCustomerFilter.DisplayMember = "CustomerName";
                    cboCustomerFilter.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void LoadFilterOrderStatus()
        {
            try
            {
                var orderStatusData = _repository.GetAll<OrderStatus>();
                IList<OrderStatus> orderStatusResult = new List<OrderStatus>();
                IList<OrderStatus> orderStatus = new List<OrderStatus>();

                orderStatus = (from d in orderStatusData
                               select new OrderStatus
                               {
                                   Id = d.Id,
                                   OrderStatusName = d.OrderStatusName
                               }).ToList();

                if (orderStatus.Count > 0)
                {
                    orderStatusResult.Add(new OrderStatus { Id = -1, OrderStatusName = "-Select status-" });
                    for (int i = 0; i < orderStatus.Count; i++)
                    {
                        orderStatusResult.Add(orderStatus[i]);
                    }
                    cboOrderStatusFilter.DataSource = orderStatusResult;
                    cboOrderStatusFilter.DisplayMember = "OrderStatusName";
                    cboOrderStatusFilter.ValueMember = "Id";
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion Functions
    }
}